const $ = require('../lib/kdom');
import cfg from '../config';
import { sid, tab, mobile, get, post, getUser, docker } from '../util/api';
import { formatDate, tabSwitch, getCurrDay, randomColor, isArrContain, isArrNoContain, findStr, backPage, getPrevDate, getNextDate, message, closeMsg, getPinYin, getUserList } from '../util/aid';
import { setTitle, urlParam, session, getHash, format, jsons, json } from '../lib/kutil';
import * as ajax from '../lib/kajax';

import Dialog from '../lib/kdialog';
const dialog = new Dialog();

//建立ws 连接
import Ws from '../lib/kws';

let _view = require('raw-loader!./home.html'); // eslint-disable-line

/* global */

let _issLs = [];   // 问题列表
const _iss = {};     // 通过 issid 获得 iss对象 
const _msg = {};     // 每个iss的 消息列表 
let _issid = null;   // 当前会话IssueID
let _userid = '';    // 当前会话的用户pid

// let heartTimer = null; //心跳定时器
let fromId = null; // 回话自己PID
let toId = null; // 回话目标PID
let targetVal = '0'; //发送给谁// 0发给专职,1发给用户，2发专家，3发给线下
let currIssue = null; // 当前工单
let userData = null;// 登陆用户
let msgTitle = null; // 消息的Title
let msgText = null; // 消息的Text
let isSelf = null; // 是否自己
let isServiceId = null; // 服务id
let quickInfo = ['您好，为了方便您了解（记忆），我现在将该内容通过短信（彩信）发给您，请您留意查询', '不好意思，担误您的时间了', '等待之前先提醒：“先生/小姐，请您稍等片刻，我马上为您查询', '请您稍等片刻，马上就好', '感谢您耐心的等候']; // 快捷回复

export default class {
  path = '/ogspc/home$';
  hash = '/ogspc/home';
  title = '工银重庆对公客户信息平台';

  constructor(opt) {
    opt = opt || {};
    this.path = opt.path || this.path;
    this.hash = opt.hash || this.hash;
    this.title = opt.title || this.title;
  }

  // 输出视图
  view(cb) {
    if (!_view) {
      // 静态资源浏览器有缓存,增加时标,强制刷新!
      getView(`${cfg.view.home}?t=${(+new Date())}`, '', (rs) => {
        _view = rs;
        cb(null, _view);
      });
    } else
      cb(null, _view);
  }

  // 在已经加载的视图上操作
  bind(dv, params) {
    // self PID
    userData = params.user || {};
    fromId = userData.pid;
    // toId = '80332128';

    if (fromId) {
      //建立ws 连接
      $._ws = new Ws({ url: WS_URL, pid: fromId, time: 10 });
      $._ws.onopen = (s) => {
        console.log(s)
      };
      // 接收消息
      $._ws.onmsg = (s) => {
        console.log('onmsg', s);
        if (s.indexOf('{') > -1) {
          //处理换行符
          s = repalceNR(s);
          s = s ? JSON.parse(s) : {};
          if (s.M == 200 || s['M.G'] == 200) { // 发出去
            sendCurrMsg(s);
          } else {//收消息
            receiveMsg(s);
          }
        }
      };
    }

    console.log('我是HOME', params, fromId, toId);

    dialog.loading();

    bindFun();
    quickInfoFun(quickInfo);
    loadListFun();
    userFun(userData);
    skillFun();
  }

  /*bind*/
}

function repalceNR(s) {
  //处理换行符的空格
  const regr = /\r|\n/;
  let rs = s;
  if (rs) {
    if (regr.test(rs)) {
      // rs = rs.replace(/\r\n/g,"");
      rs = rs.replace(/\s/g, "");
      console.log(rs);
    }
  }
  return rs;
}

// 发送消息
function sendMsg() {
  //发送给谁//1发给用户，2发专家，3发给线下,4发给专职
  // msg(f, t, fw, tp, sq, st, s)
  console.log('_iss          ', _iss);
  console.log('_issid        ', _issid);
  console.log('_iss[_issid].pid        ', _iss[_issid].pid);
  if (_iss[_issid]) {
    const m = {
      F: fromId
      , T: _iss[_issid].pid
      // , T: toId
      , FW: '1'
      , TP: _issid
      , TM: parseInt(new Date().getTime() - Date.parse('2000/01/01'))
      , SQ: 123
      , ST: 1
      , M: sendMsgVal.value
    };
    console.log('发送消息        ', m);
    // pid,消息,转发,主题，SQ,状态  
    // t, s, fw, tp, sq, st
    $._ws.msg(m.T, m.M, m.FW, m.TP, m.SQ, m.ST);
    sendMsgVal.value = '';

    if (_issid) {
      if (!_msg[_issid])
        _msg[_issid] = [];
      _msg[_issid].push(m);
      laodMsgFun(_issid, _msg[_issid].length - 1);
      saveMsgFun(m);
    }
  }
}

/********************* bind *************************/
function bindFun() {
  // 发送消息
  $.id('sendMsgBtn').onclick = () => {
    if ($.id('sendMsgVal').value) {
      sendMsg();
      // if (isServiceId)
      issueServiceId();
    } else {
      alert('请输入你要发送的消息！');
    }
  };
  //回车发送消息
  enterSend()
  // 快捷回复
  $.id('quickTag').onchange = () => {
    $.id('sendMsgVal').value = quickInfo[$.id('quickTag').value];
  };

  // 回话目标
  $.id('answerTag').onchange = () => {
    let val = $.id('answerTag').value;
    // // console.log(val);
    // // conversationTitleFun(val);
    // if (val == 11) {
    //   zhuan_ZJ_Tag();
    // } else if (val == 14) {
    //   zhuan_XX_Tag();
    // }
  };

  // 转专家
  $.id('expertTag').onclick = () => {
    let val = $.id('expertVal').value;
    // conversationTitleFun('11');
    // zhuan_ZJ_Tag($.id('zhuan_ZJ_Tag_Val').value);
    pushMsgFun('pushmsg');
    upIssueProcess(_issid, 2);
  };

  // 转线下
  $.id('lineDotTag').onclick = () => {
    // conversationTitleFun('14');
    pushMsgFun('msgOnline');
    upIssueProcess(_issid, 3);
  };

  $.id('closeIssue').onclick = () => {
    // console.log('closeIssue   ', _issid);
    closeIssueFun();
    pushMsgFun('singlePush');
  };

  // tab 切换
  tabSwitch($.qus('#listTabBox .tab-item-cell'), (that) => {
    let val = that.getAttribute('data-val');
    createListFun(_issLs, val);
  });
}

function enterSend() {
  document.onkeydown = function (e) {
    e = e || window.event;
    if (e.keyCode == 13) {
      sendMsgBtn.click();
    }
  }
}

// skillFun
function skillFun() {
  siteFun((rs) => {
    console.log('skillFun          ', rs);
    // skill
    let rc = '';
    for (let i = 0, o = rs.skill, len = o.length; i < len; i++) {
      rc += `<option value="${o[i][0]}">${o[i][1]}</option>`;
    }
    $.html($.id('expertVal'), rc);
  });
}

// 加载快捷回复内容
function quickInfoFun(data) {
  let rc = '<option value="">快捷回复</option>';
  for (let i = 0, o = data, len = o.length; i < len; i++) {
    rc += `<option value="${i}">${data[i]}</option>`;
  }
  $.html($.id('quickTag'), rc);
}

// userFun
function userFun(data) {
  let img = '';
  if (data.headimgurl) {
    img = data.headimgurl;
  } else {
    img = 'img/from-head-img.jpg'
  }
  let rc = `<div class="item-cell">
               <img class="head-img" src="${img}" style="margin-top:10px;">
             </div>
             <div class="item-right">
               <span>${data.name}</span>
             </div>`;
  $.html($.id('loginUserBox'), rc)
}

// 创建列表
function createListFun(data, val) {
  console.log('创建列表:', data, val);
  if (!data) return;

  $.html($.id('issueListBox'), '');
  $.html($.id('messageListBox'), '');
  $.html($.id('conversationTitle'), '');

  let rc = '';
  let idx = _iss[_issid] ? _iss[_issid].pid : '';
  let status = '';
  let num = 0;
  for (let i = 0, o = data, len = o.length; i < len; i++) {
    status = o[i].status;
    _iss[o[i].id] = o[i];
    if (val) {
      if (val == 1) {
        if (status == 1 || status == 0) {
          console.log('创建列表 状态1', status);
          num += 1;
          rc += createDvsFun(o[i], i, idx, num);
        }
      } else {
        console.log('创建列表 状态2', status);
        if (status == val) {
          num += 1;
          rc += createDvsFun(o[i], i, idx, num);
        }
      }
    } else {
      if (status == 1 || status == 0) {
        num += 1;
        rc += createDvsFun(o[i], i, idx, num);
      }
    }
  }

  if (rc) {
    $.html($.id('issueListBox'), rc);
    // tab 切换
    tabSwitch($.qus('#issueListBox li'), (that) => {
      let val = that.getAttribute('data-val');
      selectChatTagFun(val);
      // alert(issueId);
      // console.log('tab 页签', _issLs[val].id);
      $.html($.id('messageListBox'), '');
      loadMsgListFun(_issLs[val].id);
      $.id('messageBox').scrollTop = $.id('messageBox').scrollHeight;
    });
  } else {
    // $.html($.id('issueListBox'), '');
    // $.html($.id('messageListBox'), '');
    // alert('暂时没有获取到更多的消息!');
  }
  // $.id('messageBox').scrollTop = $.id('messageBox').scrollHeight;
  dialog.close();
}

// 创建片段
function createDvsFun(data, i, idx, num) {
  // console.log('创建片段', data, i, idx, num);
  let rc = '';
  let cls = '';
  if (!data) return rc;

  if (!idx && num == 1) {
    $.html($.id('messageListBox'), '');
    cls = ` active`;
    currIssue = data; // issue
    _issid = data.id; // issue id
    // toId = data.pid; // user id
    msgTitle = data.title;
    msgText = data.text;
    selectChatTagFun(i);
    loadMsgListFun(_issid);
  } else {
    if (idx == data.pid) {
      $.html($.id('messageListBox'), '');
      cls = ` active`;
      currIssue = data; // issue
      _issid = data.id; // issue id
      // toId = data.pid; // user id
      msgTitle = data.title;
      msgText = data.text;
      selectChatTagFun(i);
    } else {
      cls = '';
    }
  }

  rc += `<li class="item-row ${cls}" data-val="${i}" id="list_${data.id}">`;
  rc += `<div class="item-cell">
             <img class="avatar" src="${JSON.parse(data.member[0])[0] || 'img/to-head-img.jpg'}">
           </div>
           <div class="item-right">
             <p class="gs-title">${data.title}</p>
             <p class="gs-describe">${data.text}</p>
           </div>
         </li >`;
  return rc;
}

// 选择聊天
function selectChatTagFun(idx) {
  currIssue = _issLs[idx]; // 当前工单
  _issid = _issLs[idx].id; // 当前工单ID
  // toId = _issLs[idx].pid; // 当前工单PID
  // console.log('选择聊天        ', currIssue, issueId, toId);

  conversationTitleFun(_issLs[idx]);
}
// 设置聊天的title
function conversationTitleFun(data) {
  if (data instanceof Object)
    $.html($.id('conversationTitle'), `${data.title}` || '');
  else {
  }
  // $.html($.id('conversationTitle'), `${huihuaObj[data]}` || '');
}

/********************* msgs *************************/
// 接收消息
function receiveMsg(m) {
  if (m.M || m['M.G']) {
    m.M = m.M || m['M.G']; // 兼容群发的消息
    // toId = m.F; // 发送过来的id
    console.log('接收消息[屏蔽消息]         ', _issid, m);
    // 屏蔽消息
    if (_issid != m.TP) {
      return;
    }

    if (_issid) {
      if (!_msg[_issid])
        _msg[_issid] = [];
      _msg[_issid].push(m);
      laodMsgFun(_issid, _msg[_issid].length - 1);
    }
  }
}

// sendCurrMsg
function sendCurrMsg(s) {
  // console.log('发消息          ', s);
  // if (!s) return;
  // if (s.M != 200) return;
  // laodMsgFun();
}

// 加载消息
function laodMsgFun(issid, msgid, fId) {
  // console.log('加载消息', JSON.stringify(s));
  // {"M":"[[1,\"个人状态\"],[1,\"工作状态\"]]","F":"42996815","FW":"转发用户","ID":"7788","TP":"话题","SQ":"123","ST":1}

  let m = _msg && _msg[issid] && _msg[issid][msgid];
  if (!m.M) return;
  let rc = document.createElement('li');
  let cls = '';
  let forward = '';
  let img = '';
  let name = '';
  if (fId) {
    cls = 'message-right';
    name = userData.name;
    if (userData.headimgurl) {
      img = userData.headimgurl;
    } else {
      img = 'img/from-head-img.jpg';
    }
  } else {
    if (m.F == fromId) {
      cls = 'message-right';
      name = userData.name;
      if (userData.headimgurl) {
        img = userData.headimgurl;
      } else {
        img = 'img/from-head-img.jpg';
      }
    } else {
      cls = 'message-left';
      name = '';
      img = 'img/to-head-img.jpg';
    }
  }

  //发送给谁// 0发给专职,1发给用户，2发专家，3发给线下
  // let btnFwId = '';
  // if ((m.FW == '1' || m.FW == '3') && fromId != m.F && !fId) {
  //   btnFwId = `btnFw${issid}-${msgid}`;
  //   forward = `<div><button id=${btnFwId} class="file-group-button">转发</button></div>`;
  // } else {
  //   forward = '';
  // }

  let btnFwId = '';
  let btnEditId = '';
  if (m.FW == '1' && fromId != m.F && !fId) {
    btnFwId = `btnFw${issid}-${msgid}`;
    btnEditId = `btnFwEdit${issid}-${msgid}`;
    forward = `<div class="btn-fw-edit">
      <button id='${btnFwId}'>转用户</button>
      <button id='${btnEditId}'>编辑</button>
    </div>`;
  }
  /*else if (m.FW == '3' && fromId != m.F && !fId) {
    btnFwId = `btnFw${issid}-${msgid}`;
    forward = `<div><button id=${btnFwId} class="file-group-button">转发</button></div>`;
  } */
  else {
    forward = '';
  }


  rc.innerHTML = `<div class="message-item ${cls}">
 						<div class="msg-head-portrait">
 							<img class="msg-avatar tagImg-${m.F}" src="${img}">
 						</div>
 						<div class="message-text">
 							<div class="name tagName-${m.F}">${name}<span>${formatDate('hh:mm')}</span></div>
               <div class="text">${m.M}</div>
             ${forward}
             </div>
           </div>`;

  $.id('messageListBox').appendChild(rc);
  $.id('messageBox').scrollTop = $.id('messageBox').scrollHeight;

  if (!name) {
    getCurrUser(m.F, rs => {
      setCurrUserInfoFun(`tagImg-${m.F}`, `tagName-${m.F}`, rs);
    });
  }

  if (btnFwId)
    $.id(btnFwId).onclick = () => { forwardMsg(issid, msgid) };

  if (btnEditId)
    $.id(btnEditId).onclick = () => { editMsg(issid, msgid) };
}
// setCurrUserInfoFun
function setCurrUserInfoFun(img, name, rs) {
  let imgs = $.qus(`.${img}`);
  let names = $.qus(`.${name}`);
  // console.log('imgs, names', imgs, names);
  for (let i = 0, o = imgs, len = o.length; i < len; i++) {
    $.html(names[i], rs.name);
    imgs[i].setAttribute('src', rs.headimgurl);
  }
}
/********************* api *************************/
function getCurrUser(pid, cb) {
  post(`${HOST_URL}${cfg.ogs.getCurrentUser}`, `pid=${pid}&sid=${sid()}&tab=${tab()}`, (err, rs) => {
    if (rs) {
      let r = JSON.parse(rs);
      if (r.rc == 200) {
        if (cb) cb(r.data[0]);
      }
    }
  });
}
// 保存
function saveMsgFun(m) {
  let data = {
    issueId: m.TP,
    from: m.F,
    to: _iss[_issid].pid,
    msg: JSON.stringify(m),
    pic: [],
    member: JSON.stringify([userData.name, userData.headimgurl]),
    status: 1
  };
  ajax.post(`${HOST_URL}${cfg.ogs.saveMsg}`, data, (err, rs) => {
    // console.log('保存', rs);
  });
}

// issueServiceId
function issueServiceId() {
  ajax.post(`${HOST_URL}${cfg.ogs.upIssueServiceId}`, `id=${_issid}&serviceId=${fromId}`, (err, rs) => {
    if (rs) {
      // console.log(rs);
      isServiceId = false;
    } else {
      isServiceId = true;
    }
  });
}


// loadListFun
function loadListFun() {
  ajax.get(`${HOST_URL}${cfg.ogs.issueList}`, "", (rs) => {
    if (rs) {
      let r = JSON.parse(rs);
      _issLs = r;
      createListFun(r);
    } else {
      // alert('获取工单信息失败！');
    }
  });
}

// 加载消息内容列表
function loadMsgListFun(id) {
  // console.log('加载消息内容列表id', id);
  ajax.get(`${HOST_URL}${cfg.ogs.msgList}`, `issueId=${id}`, (rs) => {
    if (rs) {
      let r = JSON.parse(rs);
      let rc = {};
      // console.log('加载消息内容列表', r);
      for (let i = 0, ms = r.data, len = ms.length; i < len; i++) {
        let m = ms[i];
        if (i == 0) {
          rc = {
            F: m.from
            , T: m.to
            , FW: ''
            , TP: m.issueId
            , TM: parseInt(new Date().getTime() - Date.parse('2000/01/01'))
            , SQ: 123
            , ST: 1
            , M: m.msg.M
          };
        } else {
          rc = m.msg;
        }

        if (m.issueId) {
          if (!_msg[m.issueId])
            _msg[m.issueId] = [];
          _msg[m.issueId].push(rc);
          laodMsgFun(m.issueId, _msg[m.issueId].length - 1);
        }
      }
    } else {
      // alert('获取工单信息失败！');
    }
  });
}

// closeIssueFun
function closeIssueFun() {
  ajax.post(`${HOST_URL}${cfg.ogs.closeIssue}`, `id=${_issid}&status=2`, (err, rs) => {
    // console.log(rs);
    if (rs) {
      // let tag = $.id(`list_${issueId}`);
      // tag.parentNode.removeChild(tag);
      loadListFun();
    }
  });
}

// 获取公众号信息
function siteFun(cb) {
  let rc = sessionStorage.getItem(cfg.app.site);
  if (rc) {
    // console.log('获取公众号信息rc', rc);
    if (cb) cb(JSON.parse(rc));
  } else
    ajax.get(`${HOST_URL}${cfg.ogs.getSite}`, `sid=${sid()}&tab=${tab()}`, (rs) => {
      if (rs) {
        let r = JSON.parse(rs);
        // console.log('获取公众号信息', r);
        sessionStorage.setItem(cfg.app.site, JSON.stringify(r.ErrMsg[0]));
        if (cb) cb(r.ErrMsg[0]);
      }
    });
}

// 推送消息
function pushMsgFun(act) {
  siteFun((site) => {
    console.log('获得site的参数', site);
    const CurrIss = _iss[_issid];
    const link = encodeURIComponent('https://imapi.icbc.com.cn/open/oauth2?scope=base&appid=' + encodeURIComponent(site.appId) + '&redirect=http%3A%2F%2Frel.nuoyadalu.com%2Fogs%2Fmb%2Findex.html?issueId=' + _issid + '%26pid=' + fromId + '%26sid=' + sid() + '%26tab=' + tab() + '');
    const msgOther = {
      "title": CurrIss.title,
      "description": '您好，您有一条新的工单信息邀请您处理！',
      "url": "",
      "picurl": "PIC_URL",
    };
    let pid = $.id('expertVal').value; //部门PID
    let apiUrl = '';
    if (act == 'msgOnline') {
      apiUrl += `${HOST_URL}${cfg.ogs.msgOnline}`;
    } else if (act == 'pushmsg') {
      apiUrl += `${HOST_URL}${cfg.ogs.pushmsg}`;
    } else if (act == 'singlePush') {
      apiUrl += `${HOST_URL}${cfg.ogs.singlePush}`;
      pid = CurrIss.pid;
      msgOther.title = '服务点评';
      msgOther.description = CurrIss.text;
    }
    const data = {
      sendUrl: encodeURIComponent(site.sendmsgUrl),
      link: link,
      pid: pid,
      sid: sid(),
      msgOther: JSON.stringify(msgOther),
    };

    console.log('CurrIss:            ', CurrIss);
    console.log('pushMsgFun:            ', data);
    // ajax.post(`http://127.0.0.1:3031${cfg.ogs.singlePush}`, data, (err, rs) => {
    ajax.post(apiUrl, data, (err, rs) => {
      console.log(rs);
      if (rs) {
        let r = JSON.parse(rs);
        if (r.errcode == 0 && r.errmsg == 'success') {
          dialog.alert({ content: '推送消息成功！' });
        } else {
          dialog.alert({ content: '推送消息失败！' });
        }
      }
    });
  });
}

/********************* tool *************************/
// 格式化MSG
function formatMsg(s) {
  let rc = '';
  let rc1 = '';
  if (s.M && String(s.M).indexOf('^^^^^') > -1) {
    rc = s.M.split('^^^^^');
    rc1 = rc[1].split(',');
  }
  return { data: rc1, msg: rc[2] };
}

/**
 * 转发用户消息
 * @param {*} issid 
 * @param {*} msgid 
 */
function forwardMsg(issid, msgid) {
  console.log(`fw issid:${issid} msgid:${msgid} msglen:${_msg[issid].length}`);
  const m = _msg[issid][msgid];
  let msg = {
    F: fromId
    , T: _iss[issid].pid
    , FW: m.FW
    , TP: m.TP
    , TM: parseInt(new Date().getTime() - Date.parse('2000/01/01'))
    , SQ: m.SQ
    , ST: m.ST
    , M: m.M
  };

  console.log('转发后的 _iss[_issid].pid', _iss[_issid].pid);
  saveMsgFun(msg);
  laodMsgFun(issid, msgid, fromId);
  // pid,消息,转发,主题，SQ,状态  
  // t, s, fw, tp, sq, st
  $._ws.msg(_iss[issid].pid, m.M, m.FW, m.TP, m.SQ, m.ST);
}

// editMsg
function editMsg(issid, msgid) {
  console.log(`fw issid:${issid} msgid:${msgid} msglen:${_msg[issid].length}`);
  console.log('editMsg _iss[_issid].pid', _iss[_issid].pid);
  const m = _msg[issid][msgid];
  $.id('sendMsgVal').value = m.M;
}

// upIssueProcess
function upIssueProcess(issid, val) {
  var data = {
    "id": issid
    , "process": val //处理状态1用户,2专家,3线下
  };
  post(`${HOST_URL}${cfg.ogs.upIssueProcess}`, data, (err, rs) => {
    // console.log(JSON.parse(rs));
    // if (rs) {
    //   dialog.alert({ content: '推送消息成功！' });
    // }
  });
}